package com.ruoyi.basic.service.impl;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.basic.domain.*;
import com.ruoyi.basic.mapper.BasicUserMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.basic.mapper.BasicSalaryMapper;
import com.ruoyi.basic.service.IBasicSalaryService;
import com.ruoyi.common.core.text.Convert;

/**
 * 岗位工资Service业务层处理
 * 
 * @author ruoyi
 * @date 2023-01-17
 */
@Service
public class BasicSalaryServiceImpl extends ServiceImpl<BasicSalaryMapper, BasicSalary> implements IBasicSalaryService
{
    @Autowired
    private BasicUserMapper userMapper;

    /**
     * 查询岗位工资
     * 
     * @param salaryId 岗位工资主键
     * @return 岗位工资
     */
    @Override
    public BasicSalary selectBasicSalaryBySalaryId(Long salaryId)
    {
        return baseMapper.selectBasicSalaryBySalaryId(salaryId);
    }

    /**
     * 查询岗位工资列表
     * 
     * @param basicSalary 岗位工资
     * @return 岗位工资
     */
    @Override
    public List<BasicSalary> selectBasicSalaryList(BasicSalary basicSalary)
    {
        return baseMapper.selectBasicSalaryList(basicSalary);
    }

    /**
     * 新增岗位工资
     * 
     * @param basicSalary 岗位工资
     * @return 结果
     */
    @Override
    public int insertBasicSalary(BasicSalary basicSalary)
    {
        if (basicSalary.getIsDefault().equals("Y")){
            LambdaUpdateWrapper<BasicSalary> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.set(BasicSalary::getIsDefault, "N");
            updateWrapper.eq(BasicSalary::getUserId, basicSalary.getUserId());
            updateWrapper.eq(BasicSalary::getSalaryType, basicSalary.getSalaryType());
            updateWrapper.eq(BasicSalary::getIsDefault, "Y");
            baseMapper.update(null, updateWrapper);
        }
        basicSalary.setCreateTime(DateUtils.getNowDate());
        return baseMapper.insert(basicSalary);
    }

    /**
     * 修改岗位工资
     * 
     * @param basicSalary 岗位工资
     * @return 结果
     */
    @Override
    public int updateBasicSalary(BasicSalary basicSalary)
    {
        if (basicSalary.getIsDefault().equals("Y")){
            LambdaUpdateWrapper<BasicSalary> updateWrapper = Wrappers.lambdaUpdate();
            updateWrapper.set(BasicSalary::getIsDefault, "N");
            updateWrapper.eq(BasicSalary::getUserId, basicSalary.getUserId());
            updateWrapper.eq(BasicSalary::getSalaryType, basicSalary.getSalaryType());
            updateWrapper.eq(BasicSalary::getIsDefault, "Y");
            updateWrapper.ne(BasicSalary::getSalaryId, basicSalary.getSalaryId());
            baseMapper.update(null, updateWrapper);
        }
        basicSalary.setUpdateTime(DateUtils.getNowDate());
        return baseMapper.updateById(basicSalary);
    }

    /**
     * 批量删除岗位工资
     * 
     * @param salaryIds 需要删除的岗位工资主键
     * @return 结果
     */
    @Override
    public int deleteBasicSalaryBySalaryIds(String salaryIds)
    {
        return baseMapper.deleteBatchIds(Arrays.asList(Convert.toLongArray(salaryIds)));
    }

    /**
     * 删除岗位工资信息
     * 
     * @param salaryId 岗位工资主键
     * @return 结果
     */
    @Override
    public int deleteBasicSalaryBySalaryId(Long salaryId)
    {
        return baseMapper.deleteById(salaryId);
    }

    /**
     * 导入用户工作经历
     *
     * @param salaryList 用户工作经历数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    public String importSalary(List<BasicSalary> salaryList, String salaryType, Boolean isUpdateSupport, String operName)
    {
        if (StringUtils.isNull(salaryList) || salaryList.size() == 0)
        {
            throw new ServiceException("导入用户岗位工资数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        int row = 2;
        String REGEX_LOCALE_ENGLISH = "^[a-zA-Z]{3}\\s[a-zA-Z]{3}\\s\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\s[A-Z]{3}\\s\\d{4}$";
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BasicSalary salary : salaryList)
        {
            try
            {
                salary.setSalaryType(salaryType);
                //获取用户信息
                BasicUser user = userMapper.selectOne(new LambdaQueryWrapper<BasicUser>()
                        .eq(BasicUser::getIdCard, salary.getIdCard()).last("limit 1"));
                if(StringUtils.isNotNull(user)) {
                    salary.setUserId(user.getId());
                }else{
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、第 " + row + "行导入失败，员工 " + salary.getUserName() + " 不存在");
                    continue;
                }

                SimpleDateFormat dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);

                if(salary.getSalaryTime().matches(REGEX_LOCALE_ENGLISH)) {
                    Date salaryTime = dateFormat.parse(salary.getSalaryTime());
                    salary.setSalaryTime(DateUtils.parseDateToStr("yyyy-MM-dd", salaryTime));
                }

                // 验证工资是否存在
                BasicSalary info = baseMapper.selectOne(new LambdaQueryWrapper<BasicSalary>()
                        .eq(BasicSalary::getSalaryTime, salary.getSalaryTime())
                        .eq(BasicSalary::getSalaryType, salary.getSalaryType())
                        .eq(BasicSalary::getUserId, salary.getUserId()));
                if (StringUtils.isNull(info))
                {
                    salary.setCreateBy(operName);
                    this.insertBasicSalary(salary);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + salary.getUserName() + "员工工资 " + salary.getSalary() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    salary.setSalaryId(info.getSalaryId());
                    salary.setUpdateBy(operName);
                    this.updateBasicSalary(salary);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、" + salary.getUserName() + "员工工资 " + salary.getSalary() + " 修改成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + successNum + "、" + salary.getUserName() + "员工工资 " + salary.getSalary() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、员工 " + salary.getUserName() + " 岗位工资导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
            finally {
                row++;
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
